package helipay.api.service.impl;

import helipay.api.common.Context;
import helipay.api.common.exception.ExceptionCodeStatusEnum;
import helipay.api.common.exception.OrderDuplicateException;
import helipay.api.dao.AppPayDao;
import helipay.api.dao.OrdersDao;
import helipay.api.dao.OrdersSwipeCardDao;
import helipay.api.model.AppQueryData;
import helipay.api.model.Orders;
import helipay.api.model.OrdersSwipeCard;
import helipay.api.model.ResponseData;
import helipay.api.service.AppPayService;
import helipay.api.util.*;
import helipay.api.view.OrdersView;
import org.apache.activemq.ScheduledMessage;
import org.apache.commons.collections.map.HashedMap;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class AppPayServiceImpl extends Context implements AppPayService {

    @Autowired
    private AppPayDao appPayDao;

    @Autowired
    private OrdersSwipeCardDao ordersSwipeCardDao;

    @Autowired
    private OrdersDao ordersDao;


    @Autowired
    private JmsTemplate jmsTemplate;

    @Resource(name = "queueDestination")
    private Destination destination;

    @Override
    public String appPay(String gateway, Map<String, String> sPara, Orders orders) {
        Long startTime = System.currentTimeMillis();
        String result = HttpClientUtil.sendPostRequest(gateway, sPara, "UTF-8", "UTF-8");
        Long endTime = System.currentTimeMillis();
        //System.out.println();
        logger.info("生成二维码耗时 ：" + (endTime - startTime) + "ms");

        logger.info("请求结果 : " + result);

        ResponseData data = Json.toObject(result, ResponseData.class);
        //logger.info(data.getRt1_bizType());
        if (data.getRt2_retCode().equals("0000")) {
            orders.setSerialNumber(data.getRt6_serialNumber());
            orders.setCreatedTime(DateUtil.getCurrentDate());
            orders.setStatus(Orders.Status.DOING.toString());
            orders.setCreatedBy("admin");
            try {
                appPayDao.add(orders);
            } catch (DuplicateKeyException e) {
                throw new OrderDuplicateException(I18nUtil.getMessage(ExceptionCodeStatusEnum.DULICATEKEY.toString(), null, "zh_CN"));
            }

            return ResultUtil.getResultJson(data);
        } else {
            return ResultUtil.getResultJson(data.getRt2_retCode(), data.getRt3_retMsg());
        }

    }

    @Override
    public String appQuery(String gateway, Map<String, String> sPara) {
        String result = HttpClientUtil.sendPostRequest(gateway, sPara, "UTF-8", "UTF-8");
        logger.info("请求结果 : " + result);
        AppQueryData data = Json.toObject(result, AppQueryData.class);
        if (data.getRt2_retCode().equals("0000")) {
            return ResultUtil.getResultJson(data);
        } else {
            return ResultUtil.getResultJson(data.getRt2_retCode(), data.getRt3_retMsg());
        }
    }

    @Override
    public String addOrderInfo(final Orders orders) {
        //添加数据放进队列
        jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                ObjectMessage objectMessage = (ObjectMessage) session.createObjectMessage(orders);
                //objectMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY,10*1000);
                return objectMessage;
            }
        });
        logger.info("直接返回来");
        return ResultUtil.getResultJson("添加成功.");
    }

    @Override
    public String addSCOrderInfo(OrdersSwipeCard orders) {
        try {
            ordersSwipeCardDao.add(orders);
        } catch (DuplicateKeyException e) {
            throw new OrderDuplicateException(I18nUtil.getMessage(ExceptionCodeStatusEnum.DULICATEKEY.toString(), null, "zh_CN"));
        }

        return ResultUtil.getResultJson("添加成功.");


    }

    @Override
    public Map<String, Object> getOrdersListByAppType(String customerNumber, String appType, String startDate, String endDate, Integer index) {

        Map<String, Object> map = new HashMap<String, Object>();
        if(!"SWIPE".equals(appType)) {
            List<Orders> orders = ordersDao.getOrdersListByAppType(customerNumber, appType, startDate, endDate, index);
            List<OrdersView> list = new ArrayList<OrdersView>();
            for (Orders o : orders) {
                OrdersView ordersView = new OrdersView();
                ordersView.setCreatedTime(o.getCreatedTime());
                ordersView.setGoodsName(o.getGoodsName());
                ordersView.setOrderAmount(o.getOrderAmount());
                ordersView.setOrderId(o.getOrderId());
                ordersView.setSerialNumber(o.getSerialNumber());
                ordersView.setStatus(o.getStatus());
                list.add(ordersView);
            }

            int size = 0;
            if (orders.size() > 0) {
                size = ordersDao.getSize(customerNumber, appType, startDate, endDate);
            }
            map.put("index", index);
            map.put("size", size);
            map.put("orderList", list);
        }else{
            List<OrdersSwipeCard> orders = ordersSwipeCardDao.getOrdersListBySwipeCard(customerNumber, startDate, endDate, index);
            List<OrdersView> list = new ArrayList<OrdersView>();
            for (OrdersSwipeCard o : orders) {
                OrdersView ordersView = new OrdersView();
                ordersView.setCreatedTime(o.getCreatedTime());
                ordersView.setGoodsName("刷卡消费");
                ordersView.setOrderAmount(o.getOrderAmount());
                ordersView.setOrderId(o.getSerialNumber());
                ordersView.setSerialNumber(o.getSerialNumber());
                ordersView.setStatus(o.getBizType().equals("0")?"消费":"消费撤销");
                list.add(ordersView);
            }

            int size = 0;
            if (orders.size() > 0) {
                size = ordersSwipeCardDao.getSizeBySwipeCard(customerNumber, startDate, endDate);
            }
            map.put("index", index);
            map.put("size", size);
            map.put("orderList", list);
        }
        return map;

    }

}
